' Turn option Strict off for this module alone as we require late bound access to the Excel application object
Option Strict Off


' Part of the class the requires late bound interop with Excel
Partial Public Class ExcelOperations

    Private Const PROG_ID_EXCEL_APPLICATION As String = "Excel.Application"


    Private _excelApp As Object
    Private _excelWorkbook As Object

    ''' <summary>
    ''' Initializes the excel application object
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitializeExcel()

        Try
            _excelApp = Microsoft.VisualBasic.Interaction.CreateObject(PROG_ID_EXCEL_APPLICATION)

        Catch ex As Exception

            Throw New Exception("Unable to create " & PROG_ID_EXCEL_APPLICATION, ex)

        End Try

    End Sub

    ''' <summary>
    ''' Opens the specified workbook
    ''' </summary>
    ''' <param name="strPath">The path to the workbook to open</param>
    ''' <remarks>Initializes excel if not already open</remarks>
    Private Sub OpenWorkbook(ByVal strPath As String, ByVal openMode As WorkbookOpenMode)

        ' Throw bad parameters
        If String.IsNullOrEmpty(strPath) Then

            Throw New ArgumentNullException("strPath")

        End If


        ' Intialize Excel
        If _excelApp Is Nothing Then


            Throw New InvalidOperationException("You must initialize Excel before calling OpenWorkbook.")

        End If

        ' Attempt to open the workbook in read only mode
        Try

            _excelApp.Workbooks.Open(strPath)

        Catch ex As Exception

            Throw New Exception("Unable to open workbook: " & strPath, ex)

        End Try


    End Sub



    ''' <summary>
    ''' Returns the Excel Application Visual Basic Extensibility Project object for the current excel workbook
    ''' </summary>
    ''' <returns>The VB Extensibility VB project object</returns>
    ''' <remarks></remarks>
    Private Function GetWorkbookVBProject() As Microsoft.Vbe.Interop.VBProject


        ' Make sure we've been initialized
        If _excelApp Is Nothing Then

            Throw New InvalidOperationException("You must initialize Excel before calling GetExcelWorkbookVBProject.")

        End If

        ' Get the VBE project belonging to the workbook
        ' TODO: Is the VB project we're after always the first project in the list?
        Return _excelApp.Vbe.VBProjects.Item(1)

    End Function




End Class
